package com.glamour.hlcity.component.task.impl;
import java.util.Date;

import com.glamour.hlcity.common.condition.CommandConfigQueryCondition;
import com.glamour.hlcity.common.condition.CommandQueryCondition;
import com.glamour.hlcity.common.model.CommandConfigDO;
import com.glamour.hlcity.common.model.CommandDO;
import com.glamour.hlcity.common.util.DateFormatUtil;
import com.glamour.hlcity.common.util.ListUtil;
import com.glamour.hlcity.component.task.api.CreateExecuteUnit;
import com.glamour.hlcity.dal.dao.CommandConfigDao;
import com.glamour.hlcity.dal.dao.CommandDao;

/**
 * 命令表数据管理
 * @author zhaoxing.liuzx
 *
 */
public abstract class AbstractCmdCreateExecute implements CreateExecuteUnit {
	protected CommandDao commandDao;
	protected CommandConfigDao commandConfigDao;
	
	
	public void setCommandDao(CommandDao commandDao) {
		this.commandDao = commandDao;
	}


	public void setCommandConfigDao(CommandConfigDao commandConfigDao) {
		this.commandConfigDao = commandConfigDao;
	}

	/**
	 * 命令被选择，修改下次执行时间，命令状态和执行次数
	 */
	protected void cmdDoing(CommandDO commandDO,CommandConfigDO commandConfigDO) {
		commandDO.setStatus(CommandDO.STATUS_2);
		commandDO.setNextActDate(newActDate(commandDO, commandConfigDO));
		commandDO.setRetry(commandDO.getRetry()+1);
		commandDao.update(commandDO);
	}
	
	/**
	 * 下次执行时间
	 * @param commandDO
	 * @param commandConfigDO
	 * @return
	 */
	private Date newActDate(CommandDO commandDO,CommandConfigDO commandConfigDO){
		if(commandDO.getRetry()==null){
			return DateFormatUtil.addSeconds(new Date(), commandConfigDO.getDiffSecond());
		}else{
			return DateFormatUtil.addSeconds(new Date(), (commandDO.getRetry()+1)*commandConfigDO.getDiffSecond());
		}
		
	}
	
	/**
	 * 完结命令
	 * @param commandDO
	 */
	protected void cmdDone(CommandDO commandDO){
		commandDO.setStatus(CommandDO.STATUS_3);
		commandDao.update(commandDO);
	}
	
	protected void cmdDone(String type,String bizNo){
		CommandDO commandDO=ListUtil.first(commandDao.selectByConditon(new CommandQueryCondition().addType(type).addBizNo(bizNo)));
		if(commandDO==null){
			return;
		}
		cmdDone(commandDO);
	}

	protected CommandDO command(Long id){
		return commandDao.getById(id);
	}
	
	protected CommandConfigDO commandConfig(String type){
		return ListUtil.first(commandConfigDao.selectByConditon(new CommandConfigQueryCondition().addType(type)));
	}
	
	protected CommandDO command(String bizNo,String type){
		return ListUtil.first(commandDao.selectByConditon(new CommandQueryCondition().addBizNo(bizNo).addType(type)));
	}

}
